package com.jyy.prefabricated.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.dto.PutStockDto;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.ExtractingStatusEnum;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.ExamPaperMapper;
import com.jyy.prefabricated.mapper.QuestionMapper;
import com.jyy.prefabricated.service.QuestionService;
import com.jyy.prefabricated.service.TrainingOrganizationStockService;
import com.jyy.prefabricated.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 机构库存
 *
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class TrainingOrganizationStockController {

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TrainingOrganizationStockService trainingOrganizationStockService;

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private ExamPaperMapper paperMapper;

    @Autowired
    private QuestionService questionService;

    /**
     * 查询库存详情
     *
     * @param id
     * @return
     */
    @GetMapping("/training-organization-stock/{id}")
    public AjaxResult selectById(@PathVariable Integer id) {
        log.info("Rest request to find trainingOrganizationStock by id:{}", id);
        TrainingOrganizationStock result = trainingOrganizationStockService.selectById(id);
        return AjaxResult.success(result);
    }


    /**
     * 查询可以分配当前库存的学员列表
     *
     * @param id
     * @return
     */
    @GetMapping("/stock-student")
    public AjaxResult selectStudentByStockId(@RequestParam Integer id, Pageable pageable) {
        log.info("Rest request to find student by trainingOrganizationStockId:{}", id);
        TrainingOrganizationStock stock = trainingOrganizationStockService.selectById(id);
        if (stock == null) {
            throw new CustomException("无法识别当前库存信息");
        }
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Student> students = trainingOrganizationStockService.selectStudentByStock(stock);
        PageInfo<Student> result = new PageInfo<>(students);
        return AjaxResult.success(result);
    }

    /**
     * 查询企业购买课程包（未过期）里所包含的所有练习列表（用于企业组卷筛选）
     *
     * @param id 练习id
     * @return
     */
    @GetMapping("/query-practice")
    public AjaxResult selectStudentByStockId(@RequestParam(required = false) Integer id) {
        log.info("Rest request to find student by trainingOrganizationStockId:{}", id);
        List<ExamPaper> result = new ArrayList<>();
        SysUser user = userUtils.getCurrentUser();
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            List<TrainingOrganizationStock> stocks = trainingOrganizationStockService.selectByParams(null, 2, user.getTrainingOrganization().getId(), null);
            result = trainingOrganizationStockService.selectPracticeList(stocks);
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询自主选题题目集合
     *
     * @param mark           1题目上传，2赠送题库,0全部
     * @param practiceId        练习id
     * @param questionType   题目类型
     * @param questionBankId 题库id
     * @param stemType       题干类型
     * @param difficulty     题目难度
     * @param category       题库分类id
     * @param pageable       分页信息
     * @return
     */
    @GetMapping("/training-question")
    public AjaxResult selectQuestion(@RequestParam(required = false) Integer category,@RequestParam(required = false) Integer mark,@RequestParam(required = false) Integer type, @RequestParam(required = false) Integer practiceId, @RequestParam(required = false) Integer questionType, @RequestParam(required = false) Integer difficulty, @RequestParam(required = false) Integer stemType, @RequestParam(required = false) Integer questionBankId, @RequestParam(required = false) Integer questionState, Pageable pageable) {
        List<ExamPaper> result = new ArrayList<>();
        SysUser user = userUtils.getCurrentUser();
        Integer trainingOrganizationId = user.getTrainingOrganization().getId();
        if (mark == 1) {
            PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
            List<Question> questions = questionService.selectByParams(questionBankId, questionType, stemType, category, type, difficulty, null, questionState, trainingOrganizationId);
            PageInfo<Question> pageInfo = new PageInfo<>(questions);
            return AjaxResult.success(pageInfo);

        } else if(mark == 2) {
            if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
                List<TrainingOrganizationStock> stocks = trainingOrganizationStockService.selectByParams(null, 2, user.getTrainingOrganization().getId(), null);
                result = trainingOrganizationStockService.selectPracticeList(stocks);
            }
            List<Question> questionList = new ArrayList<>();
            if (result.size() > 0) {
                if (practiceId != null) {
                    for (ExamPaper item : result) {
                        ExamPaper examPaper = paperMapper.selectByPrimaryKey(item.getId());
                        if (examPaper.getId().equals(practiceId)) {
                            if (examPaper.getAreas().size() > 0) {
                                for (ExamPaperArea examPaperArea : examPaper.getAreas()) {
                                    if (examPaperArea.getRules().size() > 0) {
                                        //随机出题
                                        if (ExtractingStatusEnum.RANDOM.getValue().equals(examPaperArea.getExtractingStatus())) {
                                            for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                                List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), category, null, examPaperAreaRule.getDifficulty(), null, null, null);
                                                Collections.shuffle(alllist);
                                                questionList.addAll(alllist);
                                            }
                                        } else {
                                            //顺序出题
                                            for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                                List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), category, null, examPaperAreaRule.getDifficulty(), null, null, null);
                                                List<Question> randomSeries = alllist.subList(0, examPaperAreaRule.getQuestionCount());
                                                for (int i = 0; i < examPaperAreaRule.getQuestionCount(); i++) {
                                                    randomSeries.get(i).setGrade(examPaperAreaRule.getGrade());
                                                }
                                                questionList.addAll(randomSeries);
                                            }
                                        }
                                    }

                                }
                            }

                        }
                    }
                } else {
                    for (ExamPaper item : result) {
                        ExamPaper examPaper = paperMapper.selectByPrimaryKey(item.getId());
                        if (examPaper.getAreas().size() > 0) {
                            for (ExamPaperArea examPaperArea : examPaper.getAreas()) {
                                if (examPaperArea.getRules().size() > 0) {
                                    //随机出题
                                    if (ExtractingStatusEnum.RANDOM.getValue().equals(examPaperArea.getExtractingStatus())) {
                                        for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                            List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), null, null, examPaperAreaRule.getDifficulty(), null, null, null);
                                            Collections.shuffle(alllist);
                                            questionList.addAll(alllist);
                                        }
                                    } else {
                                        //顺序出题
                                        for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                            List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), null, null, examPaperAreaRule.getDifficulty(), null, null, null);
                                            List<Question> randomSeries = alllist.subList(0, examPaperAreaRule.getQuestionCount());
                                            for (int i = 0; i < examPaperAreaRule.getQuestionCount(); i++) {
                                                randomSeries.get(i).setGrade(examPaperAreaRule.getGrade());
                                            }
                                            questionList.addAll(randomSeries);
                                        }
                                    }
                                }

                            }
                        }
                    }

                }
            }
            PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
            if (questionType != null) {
                List<Question> newQuestion = new ArrayList<>();
                for (Question question : questionList) {
                    if (question.getQuestionType().equals(questionType)) {
                        newQuestion.add(question);
                    }
                }
                PageInfo<Question> pageInfo=  getPageInfo(pageable.getPageNum(),pageable.getPageSize(),newQuestion);
                return AjaxResult.success(pageInfo);
            } else {
                PageInfo<Question> pageInfo=  getPageInfo(pageable.getPageNum(),pageable.getPageSize(),questionList);
                return AjaxResult.success(pageInfo);
            }
        }
        else{
            List<Question> questions = new ArrayList<>();
            List<Question> question1 = questionService.selectByParams(questionBankId, questionType, stemType, category, type, difficulty, null, questionState, trainingOrganizationId);
            List<Question> questionList = new ArrayList<>();
            if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
                List<TrainingOrganizationStock> stocks = trainingOrganizationStockService.selectByParams(null, 2, user.getTrainingOrganization().getId(), null);
                result = trainingOrganizationStockService.selectPracticeList(stocks);
            }
            for (ExamPaper item : result) {
                ExamPaper examPaper = paperMapper.selectByPrimaryKey(item.getId());
                if (examPaper.getAreas().size() > 0) {
                    for (ExamPaperArea examPaperArea : examPaper.getAreas()) {
                        if (examPaperArea.getRules().size() > 0) {
                            //随机出题
                            if (ExtractingStatusEnum.RANDOM.getValue().equals(examPaperArea.getExtractingStatus())) {
                                for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                    List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), null, null, examPaperAreaRule.getDifficulty(), null, null, null);
                                    Collections.shuffle(alllist);
                                    questionList.addAll(alllist);
                                }
                            } else {
                                //顺序出题
                                for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                    List<Question> alllist = questionMapper.selectByParams(examPaperAreaRule.getQuestionBankId(), examPaperAreaRule.getQuestionType(), examPaperAreaRule.getStemType(), null, null, examPaperAreaRule.getDifficulty(), null, null, null);
                                    List<Question> randomSeries = alllist.subList(0, examPaperAreaRule.getQuestionCount());
                                    for (int i = 0; i < examPaperAreaRule.getQuestionCount(); i++) {
                                        randomSeries.get(i).setGrade(examPaperAreaRule.getGrade());
                                    }
                                    questionList.addAll(randomSeries);
                                }
                            }
                        }

                    }
                }
            }
            questions.addAll(question1);
            questions.addAll(questionList);
            PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
            List<Question> questionResult =  new ArrayList<>();
            questionResult.addAll(questions);
            PageInfo<Question> pageInfo=  getPageInfo(pageable.getPageNum(),pageable.getPageSize(),questionResult);
            return AjaxResult.success(pageInfo);
        }
    }
    /**
     * pagehelper   手动分页
     * @param currentPage 当前页
     * @param pageSize
     * @param list
     * @param <T>
     * @return
     */
    public static <T> PageInfo<T> getPageInfo(int currentPage, int pageSize, List<T> list) {
        int total = list.size();
        if (total > pageSize) {
            int toIndex = pageSize * currentPage;
            if (toIndex > total) {
                toIndex = total;
            }
            list = list.subList(pageSize * (currentPage - 1), toIndex);
        }
        Page<T> page = new Page<>(currentPage, pageSize);
        page.addAll(list);
        page.setPages((total + pageSize - 1) / pageSize);
        page.setTotal(total);

        PageInfo<T> pageInfo = new PageInfo<>(page);
        return pageInfo;
    }


    /**
     * 分页查询库存信息
     *
     * @param productName              产品名
     * @param type                     类型
     * @param pageable                 分页信息
     * @param trainingOrganizationName 产品名称
     * @return
     */
    @GetMapping("/training-organization-stock")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String productName, @RequestParam(required = false) Integer type, @RequestParam(required = false, defaultValue = "") String trainingOrganizationName, Pageable pageable) {
        log.info("Rest request to find trainingOrganizationStock by params productName:{},type:{}", productName, type);

        List<TrainingOrganizationStock> stocks = new ArrayList<>();
        SysUser user = userUtils.getCurrentUser();
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
            stocks = trainingOrganizationStockService.selectByParams(productName, type, user.getTrainingOrganization().getId(), trainingOrganizationName);
        } else if (UserTypeEnum.ADMIN.getValue().equals(user.getUserType())) {
            PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
            stocks = trainingOrganizationStockService.selectByParams(productName, type, null, trainingOrganizationName);
        }
        PageInfo<TrainingOrganizationStock> result = new PageInfo<>(stocks);
        return AjaxResult.success(result);
    }

    /**
     * 分配库存
     *
     * @param dto
     * @return
     */
    @PutMapping("/training-organization-stock")
    public AjaxResult putStock(@Valid @RequestBody PutStockDto dto) {
        log.info("Rest request to put stock to student by params:{}", dto);
        trainingOrganizationStockService.putStock2Student(dto);
        return AjaxResult.success();
    }

    /**
     * 修改库存信息
     *
     * @param trainingOrganizationStock
     * @return
     */
    @PutMapping("/admin-stock")
    public AjaxResult modifyStock(@Valid @RequestBody TrainingOrganizationStock trainingOrganizationStock) {
        log.info("Rest request to put stock to student by params:{}", trainingOrganizationStock);
        trainingOrganizationStockService.update(trainingOrganizationStock);
        return AjaxResult.success();
    }

}
